# -*- coding: utf-8 -*-
import time
import datetime
from datetime import date, timedelta
import os
import hashlib
import translation
from google.appengine.api import users
from google.appengine.ext.webapp import template

import webapp2 #2

from models import *
from helpers import *



class SettingsPage(webapp2.RequestHandler):
  def get(self, lang):
    set_variable('lang', lang)
    if not(users.get_current_user()):
      return webapp2.redirect(users.create_login_url('/'))
    else:
      # get user settings & FORM
      cur_user = users.get_current_user()
      user_settings = get_settings(cur_user)
      settings_form = SettingsForm(instance=user_settings,prefix='settings')
      # get user & FORM
      user = Users.all().filter('user =', users.get_current_user()).get()
      user_form = UserForm(instance=user,prefix='user')

      # form
      if user_settings:
        k_id = user_settings.key().id();
        vars = {'user_form': user_form, 'settings_form': settings_form, 'k_id': k_id, 'token': get_token(k_id)}
      else:
        vars = {'user_form': user_form, 'settings_form': settings_form}

      #show page
      template_values = {
        'title': t('Settings'),
        'top_menu': generate_menu(self),
        'lang_menu': generate_lang_menu(self),
        'lang_cur': translation.name[lang],
        'description': t('If you want send email, when you switch time, you should fill all of these fields')
      }
      trs = {
        'problems': t('Problems'),
        'lang': lang,
        'danate_text': t('Why you no'),
        'locale': t('en_US')
      }
      header = render('_header', template_values)
      footer = render('_footer', trs)
      title = render('_title', template_values)
      settings_form = render('settings_form_'+lang, vars)

      page = header + title + settings_form + footer
      self.response.out.write(page)


class SettingsPageSubmit(webapp2.RequestHandler):
  def post(self, lang):
    set_variable('lang', lang)
    simple_user = users.get_current_user()
    if not(simple_user):
      #return
      write_json(self, {'error': t("Session expired.")})
    else:
      if (self.request.get('_id')!=''):

        # validate token
        if (valid_token(self.request.get('_token'), self.request.get('_id'))==False):
          write_json(self, {'error': t("Invalid token.")})
          return

        id = int(self.request.get('_id'))
        item = Settings.get(db.Key.from_path('Settings', id))
        data_settings = SettingsForm(data=self.request.POST, instance=item, prefix='settings')
      else:
        data_settings = SettingsForm(data=self.request.POST, prefix='settings')

      loaded_user = get_user_CURRENT(simple_user)
      data_user = UserForm(data=self.request.POST, instance=loaded_user, prefix='user')
      
      if (data_settings.is_valid() and data_user.is_valid()):
        # Save the data, and redirect to the view page
        entity_settings = data_settings.save(commit=False)
        entity_settings.user = users.get_current_user()
        entity_settings.put()
        # memcache clear
        get_settings(simple_user, 'clear')

        entity_user = data_user.save(commit=False)
        entity_user.lang = lang
        entity_user.put()
        # memcache clear
        get_user_CURRENT(simple_user, 'clear')
        get_user_byTOKEN(loaded_user.auth_token, 'clear')
        
        #return
        write_json(self, {'success': t("Settings have been saved.")})

      else:
        response = {}
        for k in data_settings.errors:
            response[k] = data_settings.errors[k][0]
        for k in data_user.errors:
            response[k] = t(data_user.errors[k][0])
        write_json(self, {'error': t('Form is not valid.'), 'data': response})



class Stats(webapp2.RequestHandler):
  def get(self, lang):
    set_variable('lang', lang)
    if not(users.get_current_user()):
      return webapp2.redirect(users.create_login_url('/'))
    else:
      #show page
      css = [
      '/fullcalendar/fullcalendar.css'
      ]
      scripts = [
      '/fullcalendar/fullcalendar.min.js'
      ]

      template_values = {
      'title': t('Your stats'),
      'top_menu': generate_menu(self),
      'css': css,
      'lang_menu': generate_lang_menu(self),
      'lang_cur': translation.name[lang],
      }

      if (lang=='ru'):
        creepy_script = '''
        buttonText: {
          today: 'сегодня'
        },
        monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
        dayNamesShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб']
        '''
      else:
        creepy_script=''
      trs_main = {
        'hours_a_day': t('Hours a day'),
        'hours_a_week': t('Hours a week'),
        'creepy_script': creepy_script
      }
      trs = {
        'problems': t('Problems'),
        'lang': lang,
        'danate_text': t('Why you no'),
        'locale': t('en_US'),
        'scripts': scripts,
      }
      header = render('_header', template_values)
      footer = render('_footer', trs)
      title = render('_title', template_values)
      stats = render('stats', trs_main)

      page = header + title + stats + footer
      self.response.out.write(page)



class MainPage(webapp2.RequestHandler):
  def get(self, lang):
    
    if (self.request.path_qs):
      path_qs = '?'+self.request.query_string
    else:
      path_qs = ''

    if not(lang):
      return webapp2.redirect('/en'+path_qs)

    set_variable('lang', lang)
    simple_user = users.get_current_user()
    if (not(simple_user) and self.request.get('kick')):
      return webapp2.redirect(users.create_login_url(self.request.uri))

    elif not(simple_user):
      #show page
      template_values = {
        'title': t('Promo'),
        'lang_menu': generate_lang_menu(self),
        'lang_cur': translation.name[lang],
        'top_menu': generate_menu(self)
      }

      trs = {
        'problems': t('Problems'),
        'lang': lang,
        'danate_text': t('Why you no'),
        'locale': t('en_US')
      }

      header_path = os.path.join(os.path.dirname(__file__), 'templates/_header.html')
      footer_path = os.path.join(os.path.dirname(__file__), 'templates/_footer.html')
      content_path = os.path.join(os.path.dirname(__file__), 'templates/index_'+lang+'.html')
      page = template.render(header_path, template_values) + template.render(content_path, None) + template.render(footer_path, trs);
      self.response.out.write(page)

    else:
      # uri processor - preparing
      user = get_user_CURRENT(simple_user)
      
      
      _now = datetime.datetime.now()
      token = hashlib.sha1('auth_token'+str(simple_user.email())+str(_now.second)).hexdigest()

      if not(user): # create user and create auth_token
        user = Users()
        user.user = simple_user
        user.username = 'USERNAME'
        user.auth_token = token
        user.date_created = _now
        user.lang = lang
        user.put()
        set_variable('lang', lang)
      elif (self.request.get('set')=='token'): # renew token if we need token
        set_variable('lang', user.lang)
        # memcache
        get_user_byTOKEN(user.auth_token, 'clear')
        get_user_CURRENT(simple_user, 'clear')
        # renew token
        user.auth_token = token
        user.put()
      else:
        set_variable('lang', user.lang)
        
      user_settings = get_settings(simple_user)
      #need a token or not
      if (self.request.get('set')=='token'):
        token_query = '?token='+token
      else:
        token_query = ''

      # uri processor
      if not(user_settings):
        # if we DONT have settings go to /settings
        return webapp2.redirect(url('/settings')+token_query)
      else:
        #if we have settings go to /stats
        return webapp2.redirect(url('/stats')+token_query)

class WorkerGet(webapp2.RequestHandler):
  def get_user_text_status(self, user):

    set_variable('lang', user.lang)

    timeline = get_lasttimeline(user)

    if (timeline):
      if (timeline.date_finish is None):
         status = t('working from ') + timeline.date_start.strftime('%H:%M')
         button = t('Stop')
         timer = time.mktime(timeline.date_start.timetuple())
      else:
         status = t('left work at ') + timeline.date_finish.strftime('%H:%M')
         button = t('Work')
         timer = time.mktime(timeline.date_finish.timetuple())
    else:
      # if db was erased
      user.work_status = None
      user.put()
      # memcache
      get_user_byTOKEN(user.auth_token, 'clear')
      
      status = t('let\'s get started')
      button = t('Work')
      timer = '';

    res = {'status': status, 'button': button, 'time': timer}
    return res

  def get(self):
    if (self.request.get('auth_token')!=''):
      user = get_user_byTOKEN(self.request.get('auth_token'))
      if (user):
        status = WorkerGet.get_user_text_status(self, user)
        #return userdata
        write_json(self, {'success': '', 'data': {
        'username': user.username,
        'status': user.work_status,
        'text_status': status['status'],
        'button': status['button'],
        'time': status['time']
        }})
    if (self.request.get('auth_token')=='' or not(user)):
      #return open
        write_json(self, {'open': users.create_login_url(url('?set=token'))})

class WorkerGo_work(webapp2.RequestHandler):
  def get(self):
    if (self.request.get('auth_token')!=''):
      user = get_user_byTOKEN(self.request.get('auth_token'))
      if (user):

        cur_date = datetime.datetime.now()
        tz_offset_ar = self.request.get('tz_offset').split(':')
        timedelta = datetime.timedelta(hours=int(tz_offset_ar[0]),minutes=int(tz_offset_ar[1]))
        cur_date = cur_date + timedelta

        # write in timeline
        timeline = Timeline()
        timeline.user = user.user
        timeline.date_start = cur_date
        timeline.tz_offset = self.request.get('tz_offset')
        timeline.put()
        # memcache
        get_lasttimeline(user, 'clear')
        month_starts = get_calendar_start(cur_date)
        get_timelinedata(user.user.email(), month_starts, None, 'clear');

        user.work_status = True
        user.put()
        # memcache
        get_user_CURRENT(user.user, 'clear')
        get_user_byTOKEN(self.request.get('auth_token'), 'clear')
        
        # send email
        send_mail_in(user.user)

        #return userdata
        write_json(self, {'success': '', 'data': {
        'username': user.username,
        'status': user.work_status,
        'text_status': t('working from ') + cur_date.strftime('%H:%M'),
        'button': t('Stop'),
        'time': time.mktime(cur_date.timetuple())
        }})
    if (self.request.get('auth_token')=='' or not(user)):
      #return open
        write_json(self, {'open': users.create_login_url('/?set=token')})

class WorkerGo_relax(webapp2.RequestHandler):
  def get(self):
    if (self.request.get('auth_token')!=''):
      user = get_user_byTOKEN(self.request.get('auth_token'))
      if (user):

        cur_date = datetime.datetime.now()
        tz_offset_ar = self.request.get('tz_offset').split(':')
        timedelta = datetime.timedelta(hours=int(tz_offset_ar[0]),minutes=int(tz_offset_ar[1]))
        cur_date = cur_date + timedelta

        # write in timeline
        timeline = get_lasttimeline(user)
        timeline.date_finish = cur_date
        timeline.put()
        # memcache
        get_lasttimeline(user, 'clear')
        month_starts = get_calendar_start(cur_date)
        get_timelinedata(user.user.email(), month_starts, None, 'clear');

        user.work_status = None
        user.put()
        # memcache
        get_user_CURRENT(user.user, 'clear')
        get_user_byTOKEN(user.auth_token, 'clear')

        # send email
        send_mail_out(user.user)

        #return userdata
        write_json(self, {'success': '', 'data': {
        'username': user.username,
        'status': user.work_status,
        'text_status': t('left work at ') + cur_date.strftime('%H:%M'),
        'button': t('Work'),
        'time': time.mktime(cur_date.timetuple())
        }})
    if (self.request.get('auth_token')=='' or not(user)):
      #return open
        write_json(self, {'open': users.create_login_url('/?set=token')})






class StatsData(webapp2.RequestHandler):
  # get date_keys week days
  def get_week_days(self, year, week):
    d = date(year,1,1)
    if(d.weekday()>3):
      d = d+timedelta(7-d.weekday())
    else:
      d = d - timedelta(d.weekday())
    dlt = timedelta(days = (week-1)*7)
    days = [];
    for i in range(7):
      dat_day = d + dlt + timedelta(days=i)
      days.append(dat_day.strftime('%Y-%m-%d'))
    return days
  
  def get(self):
    if (self.request.get('start')=='' or self.request.get('end')==''):
      write_json(self, {'error': 'date interval is required'})
      return

    user = users.get_current_user()
    if not(user):
      #return open
        write_json(self, {'error': 'we lost user'})
        return
    
    events_arr = []
    start_stamp = int(self.request.get('start'))+int(self.request.get('offset_in_secs'))
    finish_stamp = int(self.request.get('end'))+int(self.request.get('offset_in_secs'))
    timeline = get_timelinedata(user.email(), start_stamp, finish_stamp)
    # collect events
    if (timeline):
      # get hours a day/week
      colors = {}
      for row in timeline:
        #no date_finish
        date_finish = row.date_finish
        if (row.date_finish is None):
          cur_date = datetime.datetime.now()
          tz_offset_ar = row.tz_offset.split(':')
          timedelta = datetime.timedelta(hours=int(tz_offset_ar[0]),minutes=int(tz_offset_ar[1]))
          cur_date = cur_date + timedelta
          setattr(row, 'date_finish', cur_date)
          colors[row.key().id()] = '#f00'

      # get sum hours by day
      #sum = {'day': {}, 'week': {}};
      sum_day = {}
      sum_week = {}
      for row in timeline:

        start_stamp = time.mktime(row.date_start.timetuple())
        finish_stamp = time.mktime(row.date_finish.timetuple())
        event_hours = (finish_stamp - start_stamp) / 3600;

        key_day = row.date_start.strftime('%Y-%m-%d');
        if (not sum_day.has_key(key_day)): sum_day[key_day]=0
        sum_day[key_day] += event_hours
		
        daytmp = date(row.date_start.year, row.date_start.month, row.date_start.day)
        week = int(daytmp.strftime("%W"))
        week_cor = int(date(row.date_start.year, 1, 1).strftime("%W"))
        week = week - week_cor + 1

        key_days = StatsData.get_week_days(self, row.date_start.year, week)
        for d in key_days:
          if (not sum_week.has_key(d)): sum_week[d]=0
          sum_week[d] += int(event_hours)

      for row in timeline:
        title = row.date_start.strftime('%H:%M')+' - '+row.date_finish.strftime('%H:%M')
        start_one = row.date_start.strftime('%Y-%m-%dT%H:%M:%S')
        end_one = row.date_finish.strftime('%Y-%m-%dT%H:%M:%S')
        id = row.key().id()
        event = {
        'id': id,
        'title': title,
        'start': start_one,
        'end': end_one
        }

        if (colors and colors.has_key(id)):
          event['color'] = colors[id]

        start_key = row.date_start.strftime('%Y-%m-%d')
        if (sum_day and sum_day.has_key(start_key)):
          event['hours_a_day'] = str(int(sum_day[start_key]))+'.'+str(int(10*(sum_day[start_key]-int(sum_day[start_key]))))   #"%.1f" % sum_day[start_key]
        if (sum_week and sum_week.has_key(start_key)):
          event['hours_a_week'] = sum_week[start_key]

        events_arr.append(event)

    write_json(self, events_arr)

class SaveLang(webapp2.RequestHandler):
  def get(self, lang):
    destination = self.request.get('destination')
    simple_user = users.get_current_user()

#    print simple_user.email()
#    loaded_user = get_user_CURRENT(simple_user)
#    print loaded_user.auth_token
#    print loaded_user.date_created
#    return

    if not(simple_user):
      return webapp2.redirect(destination)
    else:
      loaded_user = get_user_CURRENT(simple_user)
      loaded_user.lang = lang
      loaded_user.put()

      # memcache clear
      get_user_CURRENT(simple_user, 'clear')
      get_user_byTOKEN(loaded_user.auth_token, 'clear')
      return webapp2.redirect(destination)